﻿using System;
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using Utils.Singleton;

namespace Core.Scene
{
    public class SceneSystem : CommonSingleton<SceneSystem>
    {
        public event Action OnLoadStart; //当场景加载开始时触发的事件。

        public event Action<float> OnLoadProgress; //当场景加载进度变化时触发的事件

        public event Action OnLoadComplete; //当场景加载完成时触发的事件。

        public SceneInfo CurrentSceneInfo { private set; get; }

        public IEnumerator LoadSceneCoroutine(SceneInfo info)
        {
            OnLoadStart?.Invoke();
            yield return LoadScene(info.MainScene, LoadSceneMode.Single);
            if (!string.IsNullOrEmpty(info.SubScene))
                yield return LoadScene(info.SubScene, LoadSceneMode.Additive);
            yield return new WaitForSeconds(0.5f);
            OnLoadComplete?.Invoke();
        }

        private IEnumerator LoadScene(string sceneName, LoadSceneMode mode)
        {
            AsyncOperation async = SceneManager.LoadSceneAsync(sceneName, mode);
            if (async == null)
                throw new InvalidOperationException($"场景{sceneName}加载失败，请确认该场景是否已添加到构建设置中（File -> Build Settings）并且名称是否正确。");

            while (!async.isDone)
            {
                float currentProgress = async.progress / 0.9f; // 计算当前进度
                OnLoadProgress?.Invoke(currentProgress);
                yield return null;
            }
        }

        public bool IsSameScene(SceneInfo sceneInfo)
        {
            if (CurrentSceneInfo == null)
                return false;
            return IsSceneActuallyLoaded(sceneInfo.MainScene) && IsSceneActuallyLoaded(sceneInfo.SubScene);
        }

        public bool IsSceneActuallyLoaded(string sceneName)
        {
            UnityEngine.SceneManagement.Scene scene = SceneManager.GetSceneByName(sceneName);

            bool isActuallyLoaded = scene.IsValid() && scene.isLoaded;
            return isActuallyLoaded;
        }
    }
}